package com.qianxx.base.utils;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.View;

public class MarketUtil {

	/*
	 * 在哪些平台上发布该应用 就应用商店对应的packageName放入数组中 TODO
	 */
	private static String[] markets = new String[] { "com.qihoo.appstore",
			"com.tencent.android.qqdownloader" };

	private MarketUtil() {
	}

	private static MarketUtil instance;

	public static MarketUtil getInstance() {
		if (instance == null) {
			synchronized (MarketUtil.class) {
				if (instance == null) {
					instance = new MarketUtil();
				}
			}
		}
		return instance;
	}

	private boolean ifHasMarket;

	/**
	 * 是否有商店类型的软件
	 */
	public void ifHasMarket(final Activity context, final View supportView) {
		if (markets == null || markets.length == 0) {
			return;
		}

		new Thread(new Runnable() {
			@Override
			public void run() {
				// 获取packagemanager
				final PackageManager packageManager = context
						.getPackageManager();
				// 获取所有已安装程序的包信息
				List<PackageInfo> packageInfos = packageManager
						.getInstalledPackages(0);
				// 用于存储所有已安装程序的包名
				List<String> packageNames = new ArrayList<String>();
				// 从pinfo中将包名字逐一取出，压入pName list中
				if (packageInfos != null) {
					for (int i = 0; i < packageInfos.size(); i++) {
						String packName = packageInfos.get(i).packageName;
						packageNames.add(packName);
					}
				}

				// 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
				ifHasMarket = false;
				for (int i = 0; i < markets.length; i++) {
					String name = markets[i];
					if (packageNames.contains(name)) {
						ifHasMarket = true;
						break;
					}
				}

				if (context != null && supportView != null) {
					context.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							if (ifHasMarket) {
								supportView.setVisibility(View.VISIBLE);
							} else {
								supportView.setVisibility(View.GONE);
							}
						}
					});
				}

			}
		}).run();

	}

	/**
	 * 跳转到应用商店
	 */
	public void skipToMarket(Context context) {
		try {
			Uri uri = Uri.parse("market://details?id="
					+ context.getPackageName());
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		} catch (Exception e) {
			ToastUtil.getInstance().toast("没有安装应用商店");
		}
	}

}
